var sitemapHistory = {
    stack: new Array(),
    temp: null,
    //takes an element and saves it's position in the sitemap.
    //note: doesn't commit the save until commit() is called!
    //this is because we might decide to cancel the move
    saveState: function(item) {
        sitemapHistory.temp = { item: $(item), itemParent: $(item).parent(), itemAfter: $(item).prev() };
    },
    commit: function() {
        if (sitemapHistory.temp != null) sitemapHistory.stack.push(sitemapHistory.temp);
    },
    //restores the state of the last moved item.
    restoreState: function() {
        var h = sitemapHistory.stack.pop();
        if (h == null) return;
        if (h.itemAfter.length > 0) {
            h.itemAfter.after(h.item);
        }
        else {
            h.itemParent.prepend(h.item);
        }
		//checks the classes on the lists
		$('#sitemap li.sm2_liOpen').not(':has(li)').removeClass('sm2_liOpen');
		$('#sitemap li:has(ul li):not(.sm2_liClosed)').addClass('sm2_liOpen');
		// serializacja i zapisanie w bazie
		sitemapSerialize();
    }
}

//init functions
$(function() {
    $('#sitemap li').prepend('<div class="dropzone"></div>');

    $('#sitemap dl, #sitemap .dropzone').droppable({
        accept: '#sitemap li',
        tolerance: 'pointer',
        drop: function(e, ui) {
            var li = $(this).parent();
            var child = !$(this).hasClass('dropzone');
            if (child && li.children('ul').length == 0) {
                li.append('<ul/>');
            }
            if (child) {
                li.addClass('sm2_liOpen').removeClass('sm2_liClosed').children('ul').append(ui.draggable);
            }
            else {
                li.before(ui.draggable);
            }
			$('#sitemap li.sm2_liOpen').not(':has(li:not(.ui-draggable-dragging))').removeClass('sm2_liOpen');
            li.find('dl,.dropzone').css({ backgroundColor: '', borderColor: '' });
            sitemapHistory.commit();
			sitemapSerialize();
        },
        over: function() {
            $(this).filter('dl').css({ backgroundColor: '#ccc' });
            $(this).filter('.dropzone').css({ borderColor: '#aaa' });
        },
        out: function() {
            $(this).filter('dl').css({ backgroundColor: '' });
            $(this).filter('.dropzone').css({ borderColor: '' });
        }
    });
    $('#sitemap li').draggable({
         handle: ' > dl',
        opacity: .8,
        addClasses: false,
        helper: 'clone',
        zIndex: 100,
        start: function(e, ui) {
            sitemapHistory.saveState(this);
        },
		stop: function(e, ui){
		}
    });
    $('.sitemap_undo').click(sitemapHistory.restoreState);
    $(document).bind('keypress', function(e) {
        if (e.ctrlKey && (e.which == 122 || e.which == 26))
            sitemapHistory.restoreState();
    });
	$('.sm2_expander').live('click', function() {
		$(this).parent().parent().toggleClass('sm2_liOpen').toggleClass('sm2_liClosed');
		return false;
	});
});

function sitemapSerialize()
{
	$.used = new Array('start'); // tablica już użytych
	var string = '<sitemap><item><root>0</root></item>'; // wstawienie pustego węzła - zapobiega błędowi przy przeciąganiu ostatniej strony
	//var licz = 0;
	$('#sitemap li').each(function(){
		
		var current = $(this);		
		if(!current.hasClass('ui-draggable-dragging'))
		{
			for(i=0;i<$.used.length;i++){
				var show = 1;
				if($.used[i] == current.attr('alt')){
					show = 0;
					break;
				}
			}
			if(show == 1){
				if(current.hasClass('sm2_liOpen') || current.hasClass('sm2_liClosed')){
					string += '<item><root>' + current.attr('alt') + '</root>';
					string += checkChildren(current)  + '</item>';
				}else{
					string += '<item><root>' + current.attr('alt') + '</root></item>';
				}
			}
		}
	});
	// usunięcie ostatniego przecinka
	//string = string.slice(0, -1);
	string += '</sitemap>';
	$.ajax({
		type: 'POST',
		url: 'index.php/catserialize',
		data: 'data='+string,
		dataType: 'json',
		error: function(xhr, desc, e) {
		   //$('#log').text(xhr.responseText);
		   //alert(xhr.responseText);
		},
		success: function(msg){
			//$('#log').text(msg);
		}
	});
}
function checkChildren(current)
{
	var string = '<children>';
	current.find('ul li').each(function(){
		subcurrent = $(this);
		if(!subcurrent.hasClass('ui-draggable-dragging')){
			for(i=0;i<$.used.length;i++){
				var show = 1;
				if($.used[i] == subcurrent.attr('alt')){
					show = 0;
					break;
				}
			}
			if(show == 1){
				$.used.push(subcurrent.attr('alt'));
				if(subcurrent.hasClass('sm2_liOpen') || subcurrent.hasClass('sm2_liClosed')){
					string += '<child><root>' + subcurrent.attr('alt')  + '</root>';
					string += checkChildren(subcurrent) + '</child>';
				}else{
					string += '<child><root>' + subcurrent.attr('alt') + '</root></child>';
				}
			}
		}
	})
	// usunięcie ostatniego przecinka
	//string = string.slice(0, -1);
	return string + '</children>';
	
}